import React, { Component, Fragment } from "react";
import {
  Button,
  Table,
  Select,
  Divider,
  Popconfirm,
  Badge,
  Form,
  Row,
  Col,
  Input,
  message,
  Alert,
  Upload
} from "antd";
import { connect } from "dva";
import tableFilter from "../../../components/tableFilter";
import styles from "./index.less";
import api from "../services/addMessageApi";
import pubapi from "../../../services/publicApi";
import ToggleColumns from "../../../components/toggleColumns";
import { getCurrentTenant } from "../../../utils/utils";

@connect(stores => ({
  messageData: stores.messageList,
  channelDictionaryModel: stores.channelDictionaryModel,
  userData: stores.user
}))
@tableFilter
@Form.create()
class MessageSource extends Component {
  state = {
    pageNum: 1,
    pageSize: 10,
    loading: false,
    messageList: [],
    listTotal: 0,
    showColumns: [],
    columnCfg: {},
    userId: "",
    selectedRowKeys: [],
    fileUploading: false
  };

  componentDidMount() {
    this.filterFun();
    const { userId } = this.state;
    if (userId) {
      // 获取隐藏表格配置
      this.getColumnCfg(userId);
    }
  }

  componentDidUpdate(_, prevState) {
    const { userId } = this.state;
    if (userId && userId !== prevState.userId) {
      // 获取隐藏表格配置
      this.getColumnCfg(userId);
    }
  }

  static getDerivedStateFromProps(nextProps, prevState) {
    const { userInfo = {} } = nextProps.userData;
    if (userInfo.userId && userInfo.userId !== prevState.userId) {
      return { userId: userInfo.userId };
    }
    return null;
  }

  getColumnCfg = userId => {
    pubapi
      .getColumnsByTable({ user: userId, tag: "msgSourceManage" })
      .then(res => {
        if (res.success) {
          if (res.datas.length === 0 || res.datas[0].config === "") {
            this.setState({
              columnCfg: res.datas[0] || {},
              showColumns: this.getColumns()
            });
          } else {
            const hiddenArr = res.datas[0].config.split(",");
            this.setState({
              columnCfg: res.datas[0] || {},
              showColumns: this.getColumns().filter(
                c => !hiddenArr.find(hc => hc === c.dataIndex)
              )
            });
          }
        } else {
          message.error(res.errMsg);
        }
      });
  };

  onSetColumns = (shows, hiddens) => {
    const { userId, columnCfg } = this.state;
    this.setState({
      showColumns: shows
    });
    // 同步动态表格隐藏列信息
    pubapi
      .updateColumnsByTable({
        config: hiddens.map(h => h.dataIndex).join(","),
        user: userId,
        tag: columnCfg.tag || "msgSourceManage",
        id: columnCfg.id
      })
      .then(res => {
        if (!res.success) {
          message.warning("动态表格同步失败");
        }
      });
  };

  getColumns = () => {
    const { pageNum, pageSize } = this.state;
    return [
      {
        title: "序号",
        width: 50,
        render: (a, b, c) => <span>{pageSize * (pageNum - 1) + c + 1}</span>
      },
      {
        title: "租户编码",
        dataIndex: "tenantCode",
        ellipsis: true
      },
      {
        title: "租户名称",
        dataIndex: "tenantName",
        ellipsis: true
      },
      {
        title: "消息源编码",
        ellipsis: true,
        dataIndex: "sourceCode"
      },
      {
        title: "消息源名称",
        ellipsis: true,
        dataIndex: "sourceName"
      },
      {
        title: "消息源类型",
        ellipsis: true,
        dataIndex: "sourceType"
      },
      {
        title: "场景编码",
        ellipsis: true,
        dataIndex: "sceneCode"
      },
      {
        title: "场景名称",
        ellipsis: true,
        dataIndex: "sceneName"
      },
      // {
      //   title: "场景描述",
      //   ellipsis: true,
      //   dataIndex: "sceneDescription"
      // },
      {
        title: "是否自带渠道",
        ellipsis: true,
        align: "center",
        render: (_, record) => (record.haveChannel === "Y" ? "是" : "否")
      },
      {
        title: "是否自带消息模板",
        ellipsis: true,
        align: "center",
        render: (_, record) => (record.haveTemplate === "Y" ? "是" : "否")
      },
      {
        title: "是否自带消息接收组",
        ellipsis: true,
        align: "center",
        render: (_, record) => (record.haveGroup === "Y" ? "是" : "否")
      },
      {
        title: "状态",
        dataIndex: "isEnabled",
        render: text =>
          text === "Y"
            ? this.renderState(1, "启用")
            : this.renderState(-1, "停用")
      },
      {
        title: "操作",
        width: 200,
        fixed: "right",
        dataIndex: "operate",
        render: (text, record) => {
          const offLineTitle =
            record.isEnabled === "Y" ? "确定停用吗" : "确定启用吗";
          return (
            <span>
              <a onClick={() => this.onLook(record)}>查看</a>
              <Divider type="vertical" />
              <Popconfirm
                title={offLineTitle}
                onConfirm={() => this.handleCommit(record)}
              >
                {record.isEnabled === "Y" ? <a>停用</a> : <a>启用</a>}
              </Popconfirm>
              <Divider type="vertical" />
              <a onClick={() => this.onLogs(record)}>查看接收日志</a>
            </span>
          );
        }
      }
    ];
  };

  renderState = (status, text) => {
    if (status === 1) {
      return <Badge status="success" text={text} />;
    }
    if (status === -1) {
      return <Badge status="error" text={text} />;
    }
    if (status === 2) {
      return <Badge status="default" text={text} />;
    }
    return <Badge status="warning" text={text} />;
  };

  dateChange = e => {
    if (e && e.length > 0) {
      this.setState(
        {
          creTimeStart: e[0].format("YYYY-MM-DD"),
          creTimeEnd: e[1].format("YYYY-MM-DD 23:59:59"),
          pageNum: 1
        },
        () => {
          this.filterFun();
        }
      );
    } else {
      this.setState(
        {
          creTimeStart: "",
          creTimeEnd: "",
          pageNum: 1
        },
        () => {
          this.filterFun();
        }
      );
    }
  };

  handleTableChange = e => {
    const { current, pageSize } = e;
    this.setState(
      {
        pageSize,
        pageNum: current
      },
      () => {
        this.filterFun();
      }
    );
  };

  handleSearch = e => {
    this.setState(
      {
        sourceName: e,
        pageNum: 1
      },
      () => {
        this.filterFun();
      }
    );
  };

  clearChange = e => {
    if (e.target.value !== "") return;
    this.setState(
      {
        sourceName: "",
        pageNum: 1
      },
      () => {
        this.filterFun();
      }
    );
  };

  filterFun = () => {
    const { pageSize, pageNum } = this.state;
    const { form } = this.props;
    const { getFieldsValue } = form;
    // const params = {
    //   pageNum,
    //   pageSize,
    //   ...getFieldsValue()
    // };
    const params = {
      // BaseMessageSourceQuery: {
      // }
      pageNum,
      pageSize,
      ...getFieldsValue()
    };
    this.setState({ loading: true });
    api.getSceneList(params).then(res => {
      if (res.success) {
        this.setState({
          messageList: res.datas || [],
          listTotal: res.totalCount
        });
      } else {
        message.error(res.errMsg);
      }
      this.setState({ loading: false });
    });
  };

  handleCommit = record => {
    api
      .msgSceneLEnabled({
        isEnabled: record.isEnabled === "Y" ? "N" : "Y",
        id: record.id
      })
      .then(res => {
        if (res.errCode === 0) {
          message.success("操作成功");
          this.filterFun();
        } else {
          message.error(`操作失败，${res.errMsg}`);
        }
      });
  };

  onLook = rec => {
    const { history, dispatch } = this.props;
    dispatch({
      type: "channelModel/updateState",
      payload: { msgSourceRecord: rec }
    });
    // sessionStorage.setItem("msgSourceRecord", JSON.stringify(rec));
    history.push(
      `/messageCenter/messageManager/msgSourceManage/msgSourceDetail?rec=${JSON.stringify(
        rec
      )}`
    );
  };

  onLogs = rec => {
    const { history } = this.props;
    // sessionStorage.setItem("msgSourceRecord", JSON.stringify(rec));
    // history.push("/messageCenter/messageManager/msgSourceManage/msgSourceLogs");
    history.push(
      `/messageCenter/messageManager/msgSourceManage/msgSourceLogs?rec=${JSON.stringify(
        rec
      )}`
    );
  };

  deleteconfirm = record => {
    const { dispatch } = this.props;
    dispatch({
      type: "messageList/delMessage",
      payload: { msgSourceId: record.msgSourceId, sourceId: record.sourceId }
    }).then((res = {}) => {
      if (res.errCode === 0) {
        message.success("删除成功");
        this.filterFun();
      } else {
        message.error(`删除失败, ${res.msg}`);
      }
    });
  };

  onReset() {
    const { form } = this.props;
    this.resetSelectedRowKeys();
    form.resetFields();
  }

  onSelectChange = selectedKeys => {
    const { messageList = [], selectedRowKeys = [] } = this.state;
    // 获取当前页所有的 key
    const allKeysInCurrentPage = messageList.map(item => item.id);
    // 获取非当前页选中的 key
    const selectedKeysNotInCurrentPage = selectedRowKeys.filter(
      key => !allKeysInCurrentPage.includes(key)
    );
    // 获取当前页选中的的 key
    const selectedKeysInCurrentPage = selectedKeys.filter(key =>
      allKeysInCurrentPage.includes(key)
    );
    // 合并生成新的 selectedRowKeys
    this.setState(state => ({
      ...state,
      selectedRowKeys: [
        ...selectedKeysNotInCurrentPage,
        ...selectedKeysInCurrentPage
      ]
    }));
  };

  resetSelectedRowKeys = () => {
    this.setState(state => ({ ...state, selectedRowKeys: [] }));
  };

  handleSubmit() {
    this.resetSelectedRowKeys();
    this.filterFun();
  }

  render() {
    // getColumnSearchProps = () => {}, , ownerDept
    const { form } = this.props;
    const {
      pageNum,
      showColumns,
      loading,
      selectedRowKeys,
      messageList = [],
      listTotal = 0
    } = this.state;
    const { getFieldDecorator } = form;

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      }
    };
    const rowSelection = {
      onChange: this.onSelectChange,
      columnWidth: 65,
      selectedRowKeys
    };
    return (
      <div className={styles.root}>
        <div className={styles.titleBox}>消息源列表</div>
        <div style={{ padding: "24px" }}>
          <div
            style={{
              fontSize: 14,
              color: "rgba(0,0,0,0.85)",
              marginBottom: 16,
              display: "flex",
              alignItems: "center",
              padding: "14px 16px",
              background: "#fff"
            }}
          >
            <Form
              {...formItemLayout}
              onSubmit={() => this.handleSubmit()}
              style={{ width: "100%" }}
            >
              <Row>
                <Col span={6}>
                  <Form.Item label="消息源">
                    {getFieldDecorator("sourceNameOrSourceCode")(
                      <Input placeholder="请输入消息源编码或名称" />
                    )}
                  </Form.Item>
                </Col>
                <Col span={6}>
                  <Form.Item label="场景">
                    {getFieldDecorator("sceneCodeOrSceneName")(
                      <Input placeholder="请输入场景编码或名称" />
                    )}
                  </Form.Item>
                </Col>
                <Col span={6}>
                  <Form.Item label="状态">
                    {getFieldDecorator("isEnabled")(
                      <Select placeholder="请选择" allowClear>
                        <Select.Option value="Y">启用</Select.Option>
                        <Select.Option value="N">停用</Select.Option>
                      </Select>
                    )}
                  </Form.Item>
                </Col>
                <Col span={6} style={{ textAlign: "right" }}>
                  <Button
                    style={{ marginRight: "10px" }}
                    onClick={() => this.onReset()}
                  >
                    重置
                  </Button>
                  <Button
                    type="primary"
                    // htmlType="submit"
                    onClick={() => this.handleSubmit()}
                  >
                    搜索
                  </Button>
                </Col>
              </Row>
            </Form>
          </div>
          {/* <div className={styles.topSearch}>
            <div />
            <Link
              to={`/messageCenter/messageManager/messageSource/messageAdd?key=${JSON.stringify(
                keys
              )}`}
            >
              <Button type="primary">查看所有待办列表</Button>
            </Link>
          </div> */}
          <div>
            <div
              style={{
                height: 64,
                padding: "0 16px",
                display: "flex",
                justifyContent: "space-between",
                alignItems: "center",
                backgroundColor: "#fff"
              }}
            >
              <div>
                <Upload
                  showUploadList={false}
                  name="excel"
                  action="/mgt/excel/importBaseMessageSourceExcel"
                  data={{ tenantCode: getCurrentTenant().tenantCode[0] }}
                  onChange={e => {
                    const { status, response } = e.file;
                    if (status === "uploading") {
                      this.setState({ fileUploading: true });
                    } else if (status === "done") {
                      // 如果上传返回有错误，则提示错误信息，重置 loading 状态
                      if (response && response.errCode === 1) {
                        message.error(response.errMsg);
                      } else {
                        message.success("导入成功");
                        this.onReset();
                        this.filterFun();
                      }
                      this.setState({ fileUploading: false });
                    }
                  }}
                >
                  <Button
                    type="primary"
                    loading={this.state.fileUploading}
                    disabled={getCurrentTenant().id === "100000"}
                  >
                    导入
                  </Button>
                </Upload>
                <Button
                  type="dashed"
                  style={{ marginLeft: 10 }}
                  onClick={() => {
                    window.open(
                      `${
                        window.location.href.indexOf("mgt-web") !== -1
                          ? "/mgt-web/"
                          : "/"
                      }source.xlsx`,
                      "_blank"
                    );
                  }}
                >
                  导入模版下载
                </Button>
                <Button
                  type="primary"
                  style={{ marginLeft: 10 }}
                  disabled={selectedRowKeys.length === 0}
                  onClick={() => {
                    window.open(
                      `/mgt/excel/outputBaseMessageSourceExcel?param=${selectedRowKeys.join(
                        ","
                      )}`,
                      "_blank"
                    );
                  }}
                >
                  批量导出
                </Button>
                {selectedRowKeys.length !== 0 && (
                  <Fragment>
                    <Alert
                      style={{
                        display: "inline-block",
                        padding: "5px 8px",
                        marginLeft: 10
                      }}
                      message={`已选中 ${selectedRowKeys.length} 条记录`}
                      type="info"
                    />
                    &nbsp;&nbsp;
                  </Fragment>
                )}
              </div>
              <div>
                <ToggleColumns
                  originColumns={this.getColumns()}
                  showColumns={showColumns}
                  onSetColumns={this.onSetColumns}
                />
              </div>
            </div>
            <Table
              style={{ background: "#fff" }}
              columns={showColumns}
              size="middle"
              dataSource={messageList}
              rowSelection={rowSelection}
              loading={loading}
              locale={{ emptyText: "暂无数据！" }}
              scroll={
                messageList.length === 0 ? { x: false } : { x: "max-content" }
              }
              rowKey="id"
              onChange={(e, filters, sorter) =>
                this.handleTableChange(e, filters, sorter)
              }
              pagination={{
                defaultPageSize: 10,
                showQuickJumper: true,
                showSizeChanger: true,
                current: pageNum,
                total: listTotal,
                showTotal: total => `共有 ${total} 条`
              }}
            />
          </div>
        </div>
      </div>
    );
  }
}

export default MessageSource;
